
<template>
  <div class="container">
    <el-dialog
      :title="dialog.dialogType === 'edit' ? '修改返货单' : '创建返货单'"
      :visible.sync="dialog.centerDialogVisible"
      width="90%"
      center
      @open="getData"
      :lock-scroll="true"
      @close="insideHideDialog"
    >
      <div class="top">
        <el-select
          size="small"
          v-model="outer.value"
          :multiple="false"
          filterable
          remote
          reserve-keyword
          placeholder="请输入商品"
          :remote-method="remoteMethod"
          :loading="outer.loading"
        >
          <el-option
            v-for="item in outer.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          class="add"
          size="small"
          type="primary"
          icon="el-icon-circle-plus"
          @click="addShopping"
          >添加批次</el-button
        >
      </div>
      <el-table
        :data="formData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="goods_name"
          label="商品"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="code"
          label="批次编码"
          align="center"
        ></el-table-column>
        <!-- <el-table-column prop="stock_net_num" label="剩余库存" align="center"></el-table-column> -->
        <el-table-column label="返货单价" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.inp_price"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="返货数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.sum"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="选择供应商" align="center">
          <template slot-scope="scope">
            <el-select
              size="small"
              v-model="inside.value"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择供应商"
              :remote-method="insideRemoteMethod"
              :loading="inside.loading"
              @change="getOptionId(inside.value)"
            >
              <el-option
                v-for="item in inside.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="250px">
          <template slot-scope="scope">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="scope.row.notes">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleEdit(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { supplierList } from "@/api/supplier/supplierList";
import { commodityList } from "@/api/commodity/commodityList";
import {
  selectSupplierGoodsBatch,
  addReturnBill,
  findReturnBill,
  editReturnBill,
} from "@/api/returnGoods/returnGoods";

export default {
  props: {
    dialog: Object,
  },
  data() {
    return {
      formData: [],
      commodityList: [],
      outer: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: "",
      },
    };
  },
  created() {},
  methods: {
    //获取修改数据
    getData() {
      let data = {
        page: 1,
        limit: 50,
      };
      //获取商品列表
      selectSupplierGoodsBatch(data).then((res) => {
        this.outer.options = res.data.goodslist.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]`,
          };
        });
        this.commodityList = res.data.goodslist;
      });
      //获取供应商列表
      supplierList(data).then((res) => {
        this.inside.options = res.data.data.map((item) => {
          return { value: `${item.id}`, label: `${item.name}(${item.code})` };
        });
      });
      if (this.dialog.dialogType == "edit") {
        let datas = {
          id: this.dialog.id,
        };
        findReturnBill(datas).then((res) => {
          if (res.code == 0) {
            this.formData.push({
              id: res.data.info.batch_id,
              code: res.data.info.batch_code,
              goods_id: res.data.info.goods_id,
              goods_name: res.data.info.goods_name,
              erp_goods_id: res.data.info.erp_goods_id,
              erp_goods_code: res.data.info.erp_goods_code,
              inp_price: res.data.info.return_price,
              unit: res.data.info.unit,
              spec: res.data.info.spec,
              supplier_id: res.data.info.id,
              is_agriculture: res.data.info.is_agriculture,
              sum: res.data.info.return_num,
              kind: res.data.info.type == 1 ? 70 : 0,
              notes: res.data.info.notes
            });
            this.inside.value = res.data.info.supplier_name;
            this.inside.id = res.data.info.supplier_id;
          }
        });
      }
    },
    //获取供应商数据
    getSupplierList(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100,
      };
      this.inside.loading = true;
      supplierList(data).then((res) => {
        this.inside.list = res.data.data.map((item) => {
          return { value: `${item.id}`, label: `${item.name}(${item.code})` };
        });
        this.inside.loading = false;
        this.inside.options = this.inside.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },
    //选择供应商获取ID
    getOptionId(e) {
      this.inside.id = e;
    },
    //获取商品列表
    getCommodityList(query) {
      let data = {
        goods_name: query,
        page: 1,
        limit: 100,
        supplier_id: this.inside.id,
      };
      this.outer.loading = true;
      selectSupplierGoodsBatch(data).then((res) => {
        this.outer.list = res.data.goodslist.map((item) => {
          let kind = item.kind == 70 ? "(赠品)" : "";
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]${kind}`,
          };
        });
        this.outer.loading = false;
        this.outer.options = this.outer.list.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.commodityList = res.data.goodslist;
      });
    },
    // 删除
    handleEdit(scope) {
      let id = scope.row.id;
      this.formData.forEach((res, index) => {
        if (res.id == id) {
          this.formData.splice(index, 1);
        }
      });
      this.outer = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      };
      this.inside = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: "",
      };
      let data = {
        page: 1,
        limit: 50,
      };
      //获取商品列表
      selectSupplierGoodsBatch(data).then((res) => {
        this.outer.options = res.data.goodslist.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]`,
          };
        });
        this.commodityList = res.data.goodslist;
      });
      //获取供应商列表
      supplierList(data).then((res) => {
        this.inside.options = res.data.data.map((item) => {
          return { value: `${item.id}`, label: `${item.name}(${item.code})` };
        });
      });
    },
    //提交
    confirm() {
      console.log(this.formData);
      if (this.formData.length > 0) {
        if (this.inside.id != "") {
          let bool = true;
          this.formData.forEach((res) => {
            if (res.sum == 0) {
              bool = false;
              return false;
            } else {
              bool = true;
            }
          });
          if (bool) {
            let data = {
              supplier_id: this.inside.id,
              goods_name: this.formData[0].goods_name,
              goods_id: this.formData[0].goods_id,
              erp_goods_id: this.formData[0].erp_goods_id,
              erp_goods_code: this.formData[0].erp_goods_code,
              batch_code: this.formData[0].code,
              is_agriculture: this.formData[0].is_agriculture,
              return_num: this.formData[0].sum,
              return_price: this.formData[0].inp_price,
              unit: this.formData[0].unit,
              batch_id: this.formData[0].id,
              spec: this.formData[0].spec,
              type: this.formData[0].kind == 70 ? 1 : 0,
              is_normal: this.formData[0].is_normal,
              notes: this.formData[0].notes
            };
            // console.log(data);
            // return;
            if (this.dialog.dialogType == "edit") {
              data.id = this.dialog.id;
              editReturnBill(data)
                .then((res) => {
                  if (res.code == 0) {
                    this.$message({
                      message: res.msg,
                      type: "success",
                    });
                    this.insideHideDialog();
                    this.$emit("upData");
                  } else {
                    this.$message({
                      message: res.msg,
                      type: "error",
                    });
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            } else {
              addReturnBill(data)
                .then((res) => {
                  if (res.code == 0) {
                    this.$message({
                      message: res.msg,
                      type: "success",
                    });
                    this.insideHideDialog();
                    this.$emit("upData");
                  } else {
                    this.$message({
                      message: res.msg,
                      type: "error",
                    });
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          } else {
            this.$message({
              message: "请填写返回数量",
              type: "error",
            });
          }
        } else {
          this.$message({
            message: "请选择供应商",
            type: "info",
          });
        }
      } else {
        this.$message({
          message: "请添加商品",
          type: "info",
        });
      }
    },
    //添加商品
    addShopping() {
      console.log(this.commodityList);
      if (this.outer.value == "") {
        this.$message({
          message: "请选择商品",
          type: "info",
        });
      } else {
        if (this.formData.length == 1) {
          this.$message({
            message: "已添加商品",
            type: "info",
          });
        } else {
          let commodity = this.commodityList.filter((res) => {
            return res.id == this.outer.value;
          });
          console.log(commodity);
          let kind = commodity[0].kind == 70 ? "(赠品)" : "";
          commodity[0].sum = "";
          commodity[0].goods_name =
            commodity[0].goods_name + "[" + commodity[0].id + "]" + kind;
          this.formData.push(commodity[0]);
        }
        // let bool = this.formData.some(res => {
        //   return res.batch_code == this.outer.value;
        // });
        // if (bool) {
        //   this.$message({
        //     message: "已添加该商品",
        //     type: "info"
        //   });
        // } else {
        //   let commodity = this.commodityList.filter(res => {
        //     return res.batch_code == this.outer.value;
        //   });
        //   commodity[0].sum = "";
        //   commodity[0].goods_name =
        //     commodity[0].goods_name + "(" + commodity[0].id + ")";
        //   this.formData.push(commodity[0]);
        //   console.log(this.formData);
        // }
      }
    },
    //搜索商品数据
    remoteMethod(query) {
      if (query !== "") {
        this.getCommodityList(query);
      } else {
        this.outer.options = [];
      }
    },
    //搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //取消
    cancel() {
      this.insideHideDialog();
    },

    // 取消方法
    insideHideDialog() {
      this.dialog.centerDialogVisible = false;
      this.formData = [];
      this.inside = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: "",
      };
      this.outer = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
      };
    },
  },
};
</script>
<style scoped>
.top {
  position: relative;
  /* height: 40px; */
}
.main {
  display: flex;
  justify-content: center;
}
.add {
  margin: 10px 0;
  margin-left: auto;
}
</style>